package com.csu.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.web.multipart.MultipartFile;

import com.csu.common.constants.CommonParams;

/**
 * @项目名称：cphone
 * @类名称：FileUtil
 * @类描述：
 * @创建人：Tangc
 * @创建时间：2017年9月13日 下午4:23:44
 * @company:
 */
public class FileUtil
{
    /**
     * @description
     * @author TangC
     * @date 2015-8-25 下午9:36:40
     * @param productFile
     * @param systemPath
     * @param fileName
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void writeFile(MultipartFile productFile, String fileName, String folder)
            throws FileNotFoundException, IOException
    {
        OutputStream out = null;
        InputStream filecontent = null;
        try
        {

            String url = CommonParams.UPLOAD_URL + folder;
            File filePath = new File(url);

            // 如果文件夹不存在则创建
            if (!filePath.exists() && !filePath.isDirectory())
            {
                filePath.mkdir();
            }

            String fileUrl = url + File.separator + fileName;
            File file = new File(fileUrl);
            out = new FileOutputStream(file);
            filecontent = productFile.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1)
            {
                out.write(bytes, 0, read);
            }
        }
        finally
        {
            if (filecontent != null)
            {
                filecontent.close();
            }
            if (out != null)
            {
                out.close();
            }
        }

    }
}
